package com.shop.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.config.JwtUtils;
import com.shop.ex.ShoppingException;
import com.shop.feignClient.AliyunClient;
import com.shop.po.R;
import com.shop.user.Interceptor.GetUserInfoInterceptor;
import com.shop.user.mapper.UserMapper;
import com.shop.user.po.User;
import com.shop.user.po.dto.UserDto;
import com.shop.user.service.UserService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import static com.shop.common.comstant.Constant.*;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author banxia
 * @since 2023-02-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AliyunClient aliyunClient;

    @Override
    public R sendMessage(String phone, String type) {
        //根据传入的类型来判断验证码的储存位置,若为空则表示 type无效
        String redisKeyPre = IfExistType(type);
        if (Strings.isEmpty(redisKeyPre)){
            ShoppingException.ThrowShoppingException("type不符合要求，请填写实际要求");
        }
        String redisKey=redisKeyPre+phone;
        return aliyunClient.sendMessage(redisKey,phone);
    }

    @Override
    public R uploadFile(MultipartFile file, String type) {
        String pathPre = IfExistType(type);
        if (Strings.isBlank(pathPre)){
            ShoppingException.ThrowShoppingException("type不符合要求，请填写实际要求");
        }
        User user = GetUserInfoInterceptor.getUser();
        if (user==null || user.getId()==null){
            ShoppingException.ThrowShoppingException("用户登录失效");
        }
        String path=pathPre+user.getId();
        return aliyunClient.uploadOssFile(file,path);
    }

    @Override
    public void editUserInfo(UserDto userDto,String password) {
        User user = GetUserInfoInterceptor.getUser();
        if (user == null) {
            ShoppingException.ThrowShoppingException("未登录/登录失效，请重新登录");
        }
        User editUser=new User();
        if (Strings.isBlank(password)) {
            //（1）编辑用户基本信息
             BeanUtils.copyProperties(userDto,editUser);
             editUser.setId(user.getId());
             userMapper.updateById(editUser);
        }else{
            //（2）修改密码到数据库
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            editUser.setId(user.getId());
            editUser.setPassword(md5Password);
            userMapper.updateById(editUser);
        }
    }

    @Override
    public UserDto getUserInfo() {
        User user = GetUserInfoInterceptor.getUser();
        if (user == null) {
            ShoppingException.ThrowShoppingException("未登录/登录失效，请重新登录");
        }
        UserDto userDto = new UserDto();
        user = userMapper.selectById(user.getId());
        BeanUtils.copyProperties(user,userDto);
        return userDto;
    }


    //密码登录
    @Override
    public String loginByPassword(String account, String password) {
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount,account);
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            ShoppingException.ThrowShoppingException("用户账号不存在");
        }
        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
            ShoppingException.ThrowShoppingException("密码错误");
        }
        user.setPassword(null);
        //将用户信息转换为token
        String userJson = JSONObject.toJSONString(user);
        String token = JwtUtils.getJwtToken(userJson);
        return token;
    }

    //验证码登录
    @Override
    public String loginByCode(String phone, String code) {
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        //校验验证码是否正确
        String UserLoginCodePre = IfExistType(UserLoginType);
        String RightCode = redisTemplate.opsForValue().get(UserLoginCodePre + phone);
        if (Strings.isBlank(RightCode) && !RightCode.equals(code)){
            ShoppingException.ThrowShoppingException("验证码错误");
        }
        //根据手机号查询用户
        wrapper.eq(User::getPhone,phone);
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            ShoppingException.ThrowShoppingException("用户账号不存在");
        }
        user.setPassword(null);
        //将用户信息转换为token
        String userJson = JSONObject.toJSONString(user);
        String token = JwtUtils.getJwtToken(userJson);
        return token;
    }


    //注册
    @Override
    public void register(UserDto userDto, String password,String code) {
        //（1）验证 验证码是否正确
        String phone = userDto.getPhone();
        String redisKeyPre = IfExistType(UserRegisterType);
        String rightCode = redisTemplate.opsForValue().get(redisKeyPre + phone);
        if (rightCode==null || !rightCode.equals(code)){
            ShoppingException.ThrowShoppingException("验证码错误");
        }
        //（2）新增用户信息
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        user.setId(null);//自增
        String newPassword= DigestUtils.md5DigestAsHex(password.getBytes());//加密后的密码
        user.setPassword(newPassword);
        user.setStatus(1);
        user.setType("user");
        int i = userMapper.insert(user); //若这里(手机号/账号ID)不唯一也会抛出异常
        if (i==0){
            ShoppingException.ThrowShoppingException("注册失败");
        }
    }


}
